<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    :rules="rules"
    class="demo-ruleForm"
    status-icon
  >
    <el-form-item label="账号" prop="username">
      <el-input v-model="ruleForm.username" />
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="ruleForm.password" show-password/>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { reactive, ref, defineExpose } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import localCache from '@/utils/cache'
import { useStore } from 'vuex'

// ref实例
const ruleFormRef = ref<FormInstance>()
// 双向绑定的数据
const ruleForm = reactive({
  username: localCache.getCache('username') || '',
  password: localCache.getCache('password') || ''
})
// 规则
const rules = reactive<FormRules>({
  username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
})

const store = useStore()

const loginAction = async ( isRememberPassword : boolean) => {
  if (!ruleFormRef.value) return
  await ruleFormRef.value?.validate(valid => {
    if (valid) {
      // 通过表单验证
      // 记住密码
      if (isRememberPassword) {
        localCache.setCache('username',ruleForm.username)
        localCache.setCache('password',ruleForm.password)
      } else {
        localCache.deleteCache('username')
        localCache.deleteCache('password')
      }
      // 登录请求操作
      store.dispatch('loginModule/accountLoginAction', {...ruleForm } )

    } else {
      // 未通过表单验证
    }
  })
}


defineExpose({
  loginAction
})
</script>

<style lang="scss" scoped></style>
